layui.define(["table", "form", "laydate", "element"], function (exports) {
  var $ = layui.$,
    table = layui.table,
    laydate = layui.laydate,
    element = layui.element,
    form = layui.form,
    indexItemm = [],
    indexItem = [];
  function clearSession() {
    layui.sessionData("endDate", {
      key: "key",
      remove: true,
    });
    layui.sessionData("startDate", {
      key: "key",
      remove: true,
    });
    layui.sessionData("meetingName", {
      key: "key",
      remove: true,
    });
  }
  clearSession();

  /**
   *
   * @param {Array} array
   * @param {Number} params
   * @returns index
   */
  // 查找数组中的索引值
  function findIndex(array, params) {
    return array.findIndex((value, index) => {
      return value === params;
    });
  }
  var meetingType = 2,
    meetingDone = 2;
  var tableId = "table" + meetingType + meetingDone;
  $(".cy_hy").addClass("active");
  $(".wzk").addClass("active");
  tabFun(tableId, meetingType, meetingDone);

  $(".leftDiv>div").on("click", function () {
    meetingType = $(this).attr("data-meetingType");
    $(this).addClass("active").siblings().removeClass("active");
    tableId = "table" + meetingType + meetingDone;
    tabFun(tableId, meetingType, meetingDone);
  });

  let arrX = [];
  $(".rightDiv>div").on("click", function () {
    let num = $(this).attr("data-id");
    if (arrX.indexOf(num) != -1) {
      arrX.splice(arrX.indexOf(num), 1);
      $(this).removeClass("active");
    } else {
      arrX = [num];
      $(this).addClass("active").siblings().removeClass("active");
    }
    meetingDone = $(this).attr("data-meetingDone");
    tableId = "table" + meetingType + meetingDone;
    tabFun(tableId, meetingType, meetingDone);
  });
  var tableId = "table2";
  function tabFun(tableId, meetingType, meetingDone) {
    tableId = tableId;
    $(".tabCont").html(
      "<table id=" + tableId + " lay-filter=" + tableId + "></table>"
    );
    if (meetingDone == "1") {
      colStartTitle = "实计开始时间";
      colEndTitle = "实计结束时间";
      meetingOpera = "#meetingOperaDone";
    } else {
      colStartTitle = "计划开始时间";
      colEndTitle = "计划结束时间";
      meetingOpera = "#meetingOperaNot";
    }
    var tableIns = table.render({
      elem: "#" + tableId,
      skin: "nob", // 无边框风格
      height: "full-85", //
      toolbar: "#toolbarOpear", //开启工具栏
      defaultToolbar: [],
      // totalRow: true, //开启合计行
      url: base_url + "/meeting/listMeetings", //模拟接口
      headers: {
        Accept: "application/json; charset=utf-8",
        Authorization: layui.sessionData("userToken").key,
      },
      method: "post",
      contentType: "application/json",
      request: {
        pageName: "pageIndex", //页码的参数名称，默认：page
        limitName: "pageSize", //每页数据量的参数名，默认：limit
      },
      parseData: function (res) {
        return {
          code: 0,
          count: res.data.total,
          data: res.data.data,
          msg: "",
        };
      },
      cols: [
        [
          { type: "checkbox", fixed: "left" },
          {
            type: "numbers",
            title: "序号",
            width: "3%",
            fixed: "left",
            unresize: true,
          },
          {
            field: "projectName",
            title: "所属项目",
            width: "16%",
            align: "center",
            fixed: "left",
            unresize: true,
            templet: function (item) {
              return (
                "<div title=" +
                item.projectName +
                " class='whiteSpace'>" +
                item.projectName +
                "</div>"
              );
            },
          },
          {
            field: "meetingName",
            title: "会议名称",
            width: "15%",
            align: "center",
            unresize: true,
            templet: function (item) {
              return (
                "<div title=" +
                item.meetingName +
                " class='whiteSpace'>" +
                item.meetingName +
                "</div>"
              );
            },
          },
          {
            field: "meetingOriginator",
            title: "会议发起人",
            width: "8%",
            align: "center",
            unresize: true,
          },
          {
            field: "meetingUnits",
            title: "参会单位",
            width: "15%",
            align: "center",
            unresize: true,
            templet: function (item) {
              return (
                "<div title=" +
                item.meetingUnits +
                " class='whiteSpace'>" +
                item.meetingUnits +
                "</div>"
              );
            },
          },
          {
            field: "roomId",
            title: "会议室ID",
            width: "8%",
            align: "center",
            unresize: true,
          },
          {
            field: "type",
            title: "会议类型",
            width: "12%",
            align: "center",
            unresize: true,
          },
          {
            field: "startTime",
            title: colStartTitle,
            width: "12%",
            align: "center",
            unresize: true,
          },
          {
            field: "endTime",
            title: colEndTitle,
            width: "12%",
            align: "center",
            unresize: true,
            // filter: { type: "date[yyyy-MM-dd HH:mm:ss]" },
          },
          {
            field: "duration",
            title: "会议总时长",
            width: "10%",
            align: "center",
            unresize: true,
          },
          {
            field: "maxOnline",
            title: "最大在线用户数",
            width: "12%",
            align: "center",
            unresize: true,
          },

          {
            fixed: "right",
            title: "操作",
            width: "14%",
            align: "center",
            toolbar: meetingOpera,
            unresize: true,
          },
        ],
      ],
      page: true,
      limit: 5,
      limits: [5, 10, 15, 20, 25, 30],
      text: {
        none: "暂无数据",
      },
      where: {
        meetingDone,
        refresh: 2,
        meetingType,
        userNumber: layui.sessionData("userName").key,
      },
      done: function (res, curr, count) {
        // 表格渲染完成之后的回调
        var that = this.elem.next();
        if (res.data.length !== 0) {
          res.data.forEach(function (item, index) {
            if (index % 2 == 0) {
              var tr = that
                .find(".layui-table-box tbody tr[data-index='" + index + "']")
                .css("background-color", "transparent");
            } else {
              var tr = that
                .find(".layui-table-box tbody tr[data-index='" + index + "']")
                .css("background", "#EDF2FB");
            }
          });
        }
        //起止时间
        var start = laydate.render({
          elem: "#startDate",
          done: function (value, date) {
            layui.sessionData("startDate", {
              key: "key",
              value: value,
            });
            endMax = end.config.max;
            end.config.min = date;
            end.config.min.month = date.month - 1;
          },
        });
        var end = laydate.render({
          elem: "#endDate",
          done: function (value, date) {
            layui.sessionData("endDate", {
              key: "key",
              value: value,
            });
            if ($.trim(value) == "") {
              var curDate = new Date();
              date = {
                date: curDate.getDate(),
                month: curDate.getMonth() + 1,
                year: curDate.getFullYear(),
              };
            }
            start.config.max = date;
            start.config.max.month = date.month - 1;
          },
        });
      },
    });
    // 搜索
    form.on("submit(conditionalSearch)", function (data) {
      layui.sessionData("meetingName", {
        key: "key",
        value: data.field.meetingName,
      });
      tableIns.reload({
        where: {
          meetingDone,
          refresh: 2,
          meetingType,
          startTime: data.field.startTime,
          endTime: data.field.endTime,
          meetingName: data.field.meetingName,
          userNumber: layui.sessionData("userName").key,
        },
        done: function (res, curr, count) {
          // 起止时间
          laydate.render({
            elem: "#startDate",
            value:
              layui.sessionData("startDate").key == undefined
                ? ""
                : layui.sessionData("startDate").key,
            done: function (value) {
              layui.sessionData("startDate", {
                key: "key",
                value: value,
              });
            },
          });
          laydate.render({
            elem: "#endDate",
            value:
              layui.sessionData("endDate").key == undefined
                ? ""
                : layui.sessionData("endDate").key,
            done: function (value) {
              layui.sessionData("endDate", {
                key: "key",
                value: value,
              });
            },
          });
          $("#meetingName").val(
            layui.sessionData("meetingName").key == undefined
              ? ""
              : layui.sessionData("meetingName").key
          );
        },
      });
    });
    // 清空搜索
    form.on("submit(conditionalClear)", function (data) {
      clearSession();
      var whereObj = {
        meetingDone,
        refresh: 2,
        meetingType,
        startTime: "",
        endTime: "",
        meetingName: "",
        userNumber: layui.sessionData("userName").key,
      };
      tableIns.reload({
        where: whereObj,
      });
    });

    // 默认就是单选的情况
    var indexList = "";
    //全选
    form.on("checkbox(c_all)", function (data) {
      var a = data.elem.checked;
      if (a == true) {
        $(".layui-table-fixed .c_one").prop("checked", true);
        form.render("checkbox");
      } else {
        $(".layui-table-fixed .c_one").prop("checked", false);
        form.render("checkbox");
      }
    });
    //有一个未选中全选取消选中
    let indexListArr = [];
    form.on("checkbox(ldEvent)", function (data) {
      // $(data.elem).data("id")  获取自定义属性值 (String)
      // $(data.elem).prop("checked") 获取当前多选框的状态 (Boolean)
      let checked = $(data.elem).prop("checked"); //  当前元素的状态
      let dataId = parseInt($(data.elem).data("id").split("ck")[1]) + 1;
      if (checked) {
        (indexListArr.indexOf(dataId) == 0 ? 1 : indexListArr.indexOf(dataId))
          ? indexListArr.push(dataId)
          : indexListArr;
      } else {
        (indexListArr.indexOf(dataId) == 0 ? 1 : indexListArr.indexOf(dataId))
          ? indexListArr.splice(findIndex(indexListArr, dataId), 1)
          : indexListArr;
      }

      console.log("indexListArr", indexListArr, dataId);
      if (indexListArr.length !== $(".layui-table-fixed .c_one").length) {
        indexList = "";
        indexListArr.map((value) => {
          indexList += "indexList=" + value + "&";
        });
        console.log(indexList);
      } else {
        indexList = "";
      }
      console.log(indexList);
      var item = $(".layui-table-fixed .c_one");
      for (var i = 0; i < item.length; i++) {
        if (item[i].checked == false) {
          $("#c_all").prop("checked", false);
          form.render("checkbox");
          break;
        }
      }
      //如果都勾选了  勾上全选
      var all = item.length;
      console.log(all);
      for (var i = 0; i < item.length; i++) {
        if (item[i].checked == true) {
          all--;
        }
      }
      if (all == 0) {
        $("#c_all").prop("checked", true);
        form.render("checkbox");
      }
    });

    table.on("toolbar(" + tableId + ")", function (obj) {
      var checkStatus = table.checkStatus(obj.config.id);
      switch (obj.event) {
        case "getCheckData":
          // var a = data.elem.checked;
          // if (a == true) {
          //   $(".c_one").prop("checked", true);
          //   form.render("checkbox");
          // } else {
          //   $(".c_one").prop("checked", false);
          //   form.render("checkbox");
          // }
          break;
        // 刷新
        case "refresh":
          tableIns.reload({
            where: {
              refresh: 1,
              meetingDone,
              meetingType,
              startTime: $("#startDate").val(),
              endTime: $("#endDate").val(),
              meetingName: $("#meetingName").val(),
              userNumber: layui.sessionData("userName").key,
            },
            pageIndex: {
              curr: 1, //重新从第 1 页开始
            },
          });
          break;
        // case "conditionalSearch":
        //   // ;

        //   tableIns.reload({
        //     pageIndex: {
        //       curr: 1, //重新从第 1 页开始
        //     },
        //     where: {
        //       meetingDone,
        //       refresh: 2,
        //       meetingType,
        //       startTime:
        //         layui.sessionData("startDate").key == undefined
        //           ? ""
        //           : layui.sessionData("startDate").key,
        //       endTime:
        //         layui.sessionData("endDate").key == undefined
        //           ? ""
        //           : layui.sessionData("endDate").key,
        //       meetingName: $("#meetingName").val(),
        //       userNumber: layui.sessionData("userName").key,
        //     },
        //   });
        //   ;
        //   break;
        case "downloadFiles":
          var checkStatusData = checkStatus.data;
          if (checkStatusData.length === 0) {
            layer.msg("请选择一行");
          } else {
            indexList = checkStatusData.map((v) => v.index);
            var tableCols = tableIns.config.cols,
              fieldArray = [];
            fieldArray = tableCols[0].map((v) => {
              if (v.hide == false) {
                return {
                  field: v.field,
                  key: v.key,
                };
              }
            });
            function setNewArr(params) {
              let newArr = [];
              if (params instanceof Array) {
                // 是数组的话
                params.forEach((value, index) => {
                  if (value !== undefined) {
                    newArr.push(value);
                  }
                });
                return newArr;
              } else {
                return params;
              }
            }
            var newFieldArray = setNewArr(fieldArray).map(
              (checkItem, index) => {
                if (typeof checkItem.field !== "undefined") {
                  return checkItem;
                }
              }
            );
            fields = setNewArr(newFieldArray).map(
              (v) => v.key.split("-")[1] - 1
            );

            userNumber = layui.sessionData("userName").key;

            var method = "post"; //请求方法
            // var url = "http://192.168.18.88:7071/meeting/download"; //请求url
            var url = base_url + "/meeting/download";
            var xhr = new XMLHttpRequest(); //定义一个XMLHttpRequest对象
            xhr.open(method, url, true);
            xhr.responseType = "blob"; //设置ajax的响应类型为blob
            xhr.setRequestHeader(
              "Content-Type",
              "application/json;charset=utf-8"
            );
            xhr.onload = function () //当请求完成，响应就绪进入
            {
              if (this.status == 200) {
                //当响应状态码为200时进入
                var blob = this.response; //获取响应返回的blob对象
                //这一段用来判断是否是IE浏览器，因为下面有些代码不支持IE
                if (typeof window.navigator.msSaveBlob !== "undefined") {
                  window.navigator.msSaveBlob(blob, "会议列表.xlsx");
                  return;
                }
                var a = document.createElement("a"); //在dom树上创建一个a标签
                var url = window.URL.createObjectURL(blob); //我的理解是生成一个相对于浏览器的虚拟url，用于指向传入的blob对象，让浏览器可以通过这个url找到这个blob对象
                a.href = url; //将url赋值给a标签的href属性
                a.download = "会议列表.xlsx"; //设置设置下载文件的名称
                a.click(); //主动触发a标签点击事件
              }
            };
            xhr.send(
              JSON.stringify({
                indexList,
                fields,
                meetingDone,
                meetingType,
                userNumber,
                refresh: 2,
                startTime: "",
                endTime: "",
                meetingName: "",
              })
            ); //附带参数发送请求
          }
      }
    });

    table.on("tool(" + tableId + ")", function (obj) {
      if (obj.event === "meetingChange") {
        layer.open({
          title: "会议变更",
          type: 1,
          fix: false,
          skin: "layui-layer-rim",
          area: ["40%", "45%"],
          content: $("#meetingChangeForm").html(),
          success: function (layero, index) {
            $(".changeMeetingBtn").on("click", function () {
              openMeetAddresSelect(obj.data.meetingId);
            });
            $(".cancelchangeMeetingBtn").on("click", function () {
              layer.confirm(
                "是否确定取消此次会议安排",
                { icon: 10, title: "提示" },
                function () {
                  $.ajax({
                    type: "GET",
                    url: base_url + "/meeting/delete/" + obj.data.meetingId,
                    headers: {
                      Accept: "application/json; charset=utf-8",
                      Authorization: layui.sessionData("userToken").key,
                    },
                    success: function (res) {
                      if (res.code == 200) {
                        layer.msg("取消此次会议成功！", {
                          icon: 1,
                        });
                        layer.closeAll();
                        tableIns.reload();
                        return false;
                      } else {
                        layer.msg(res.msg, { icon: 2 });
                      }
                    },
                  });
                },
                function () {
                  layer.closeAll();
                }
              );
            });
          },
        });
      } else if (obj.event === "meetingDetails") {
        var data = obj.data;
        layui.sessionData("meetingDetailsData", {
          key: "key",
          value: data,
        });
        if (meetingDone == 2) {
          location.href = "meetingInformation.html";
        } else if (meetingDone == 1) {
          location.href = "meetingInformationDone.html";
        }

        // $(this).attr(
        //   "lay-href",
        //   "../views/meetingInformation.html?meetingId=" + obj.data.meetingId
        // );
      }
    });
  }

  function openMeetAddresSelect(meetingId) {
    meetAddresSelect = layer.open({
      title: '<i class="fa fa-plus"></i>&nbsp;会议选择',
      type: 1,
      fix: false,
      skin: "layui-layer-rim",
      area: ["40%", "45%"],
      content: $("#meetAddressSelect").html(),
      success: function (layero, index) {
        $(".onlineMeeting").on("click", function () {
          flagg = 1;
          type = 1;
          openLayer(flagg, meetingId, type);
          layer.close(index); //如果设定了yes回调，需进行手工关闭
        });
        $(".offlineMeeting").on("click", function () {
          flagg = 2;
          type = 2;
          openLayer(flagg, meetingId, type);
        });
      },
    });
  }
  function openLayer(flagg, meetingId, type) {
    addIndex = layer.open({
      title: '<i class="fa fa-plus"></i>&nbsp;会议变更',
      skin: "meetingNotice",
      type: 1,
      fix: false,
      skin: "layui-layer-rim",
      // 加上边框
      area: ["45%", "75%"],
      // 宽高
      content: $("#addMeetingForm").html(),
      success: function (layero, index) {
        initDateCtrl(flagg);
        var innerUsersDataNv = [],
          dataJson = {};
        $.ajax({
          type: "GET",
          async: false, //异步执行
          url: base_url + "/user/selectUsers",
          headers: {
            Accept: "application/json; charset=utf-8",
            Authorization: layui.sessionData("userToken").key,
          },
          success: function (data) {
            if (data.code == 200) {
              var data = data.data,
                externalUsersData = data.externalUsers;
              externalUsersDataN = externalUsersData.map((item, index) => {
                return {
                  name: item.username,
                  value: index,
                };
              });
              participantsNSelect = xmSelect.render({
                el: "#participantsN",
                name: "pipelinesort",
                filterable: true,
                theme: {
                  color: "#334d80",
                },
                language: "zn",
                data: externalUsersDataN,
              });
              var innerUsersData = data.innerUsers;
              innerUsersDataN = innerUsersData.map((item) => {
                return {
                  name: item.username,
                  value: item.userNumber,
                };
              });
              participantsWSelect = xmSelect.render({
                el: "#participantsW",
                name: "pipelinesort",
                filterable: true,
                layVerify: "required",
                layVerType: "msg",
                theme: {
                  color: "#334d80",
                },
                language: "zn",
                data: innerUsersDataN,
              });
              attributionProjectSelect = xmSelect.render({
                el: "#attributionProject",
                radio: true,
                name: "projectId",
                theme: {
                  color: "#334d80",
                },
                language: "zn",
                tips: "请选择归属项目",
                searchTips: "请选择归属项目",
                autoRow: true,
                remoteSearch: true, //开启远程搜索
                filterable: true, //开启搜索
                create: function (val, arr) {
                  if (arr.length === 0) {
                    return {
                      name: val,
                      value: val,
                    };
                  }
                },
                remoteMethod: function (val, cb, show) {
                  //这里如果val为空, 则不触发搜索
                  if (!val) {
                    return cb([]);
                  }
                  $.ajax({
                    type: "GET",
                    async: false, //异步执行
                    url: base_url + "/projects/search?key=" + val,
                    headers: {
                      Accept: "application/json; charset=utf-8",
                      Authorization: layui.sessionData("userToken").key,
                    },
                    success: function (data) {
                      if (data.code == 200) {
                        projectFlowlist = data.data;
                        //将循环后的数据取出name与value，把整个放到新数组里，最后放到cb()中
                        var obj = [];
                        projectFlowlist.forEach(function (v, i) {
                          console.log(v.tip);
                          if (v.hasOwnProperty("projectType")) {
                            obj.push({
                              name: v.projectName + "-" + v.projectType,
                              value: v.projectId,
                            });
                          } else {
                            obj.push({
                              name: v.projectName,
                              value: v.projectId,
                            });
                          }
                        });
                        cb(obj);
                        // else if (v.tip) {
                        //   obj.push({
                        //     name: `<span>${v.projectName}</span><span>${v.tip}</span>`,
                        //     value: v.projectId,
                        //   });
                        // }
                      } else {
                        layer.msg(res.msg, {
                          time: 2000,
                          icon: 5,
                        });
                      }
                    },
                  });
                },
              });
            }
          },
        });
        $.ajax({
          url: base_url + "/meeting/" + meetingId,
          async: false,
          type: "GET",
          headers: {
            Accept: "application/json; charset=utf-8",
            Authorization: layui.sessionData("userToken").key,
          },
          success: function (data) {
            if (data.code == 200) {
              var data = data.data;
              $("#meetingTime").html(
                data.startTime.split(" ")[1] + "-" + data.endTime.split(" ")[1]
              );
              if (data.hasOwnProperty("projectName")) {
                attributionProjectSelect.setValue([
                  { name: data.projectName, value: data.projectId },
                ]);
              }
              var attendeesArray = [],
                attendingUnitArray = [];
              data.participantList.map((item, index) => {
                if (item.userId === "") {
                  attendeesArray.push(item);
                } else {
                  if (item.hasOwnProperty("userName")) {
                    attendingUnitArray.push(item);
                  }
                }
              });
              attendeesArrayData = attendeesArray.map((item, index) => {
                return {
                  name: item.userName,
                  value: index,
                };
              });
              attendingUnitData = attendingUnitArray.map((item, index) => {
                return {
                  name: item.userName,
                  value: item.userId,
                };
              });
              participantsNSelect.setValue(attendeesArrayData);
              participantsWSelect.setValue(attendingUnitData);
              dataJson.meetingDate = data.startTime.split(" ")[0];
              dataJson.meetingHeadline = data.meetingHeadline;
              dataJson.address = data.roomId;
              dataJson.content = data.content;
              dataJson.orgUserNumber = data.orgUserNumber;
              dataJson.meetingRemarks = data.meetingUnits;
              dataJson.remarks = data.remarks;
              dataJson.ackMsgs = data.ackMsgs;
              form.val("addMeetingForm", dataJson);
            }
          },
        });
        // 表单提交事件
        form.on("submit(formSubmit)", function (d) {
          externalUsersDataO = participantsNSelect
            .getValue()
            .map((item, index) => {
              return {
                userName: item.name,
                userId: "",
              };
            });
          innerUsersDataO = participantsWSelect
            .getValue()
            .map((item, index) => {
              return {
                userName: item.name,
                userId: item.value,
              };
            });
          d.field.participantList = externalUsersDataO.concat(innerUsersDataO);

          d.field.startTime =
            $("#meetingDate").val() +
            " " +
            $("#meetingTime").html().split("-")[0] +
            ":" +
            "00";
          d.field.endTime =
            $("#meetingDate").val() +
            " " +
            $("#meetingTime").html().split("-")[1].split(" ")[0] +
            ":" +
            "00";
          if (d.field.projectId !== "") {
            d.field.projectId = attributionProjectSelect.getValue("valueStr");
            delete d.field.projectName;
          } else {
            delete d.field.projectId;
            d.field.projectName = attributionProjectSelect.getValue("nameStr");
          }
          d.field.site = $("#meetingTime").html().split("-")[1].split(" ")[1];
          delete d.field.meetingDate;
          delete d.field.pipelinesort;
          d.field.id = meetingId;
          d.field.type = type;
          $.ajax({
            type: "POST",
            url: base_url + "/meeting/updMeeting",
            contentType: "application/json; charset=utf-8",
            async: true,
            data: JSON.stringify(d.field),
            headers: {
              Accept: "application/json; charset=utf-8",
              Authorization: layui.sessionData("userToken").key,
            },
            success: function (res) {
              layer.closeAll("loading");
              if (res.code == "200") {
                layer.msg(res.message, { icon: 1 });
                $(".meetingNotice")
                  .removeClass("layui-btn-disabled")
                  .attr("disabled", false);
                $(".enterMeeting")
                  .addClass("layui-btn-disabled")
                  .attr("disabled", true);
                $(".meetingNotice").on("click", function () {
                  window.location.href =
                    base_url + "/meeting/download/2/" + res.data;
                  layer.closeAll("page");
                  tableIns.reload();
                });
                return false;
              } else {
                layer.msg(res.message, { icon: 2 });
              }
            },
          });
          return false;
        });
      },
    });
  }
  function initDateCtrl() {
    //日期时间选择器
    laydate.render({
      elem: "#meetingDate", //指定元素
      min: 0,
      ready: function (value) {
        disabled_date(value, $("#appointmentDate").val());
      },
      change: function (value, date) {
        disabled_date(date, $("#appointmentDate").val());
      },
      done: function (value, date) {
        if (flagg == 1) {
          changeTimeForm = layer.open({
            title: "",
            type: 1,
            fix: false,
            skin: "layui-layer-rim",
            // 加上边框
            area: ["43%", "37%"],
            // 宽高
            content: $("#changeTimeForm").html(),
            success: function (layero, index) {
              renderData();
            },
            cancel: function (index, layero) {
              var chooseAfterValueNew = indexItemm.sort((a, b) => {
                return a > b ? 1 : -1;
              });
              if (chooseAfterValueNew.length == 0) {
                $("#meetingTime").html("");
              } else {
                $("#meetingTime").html(
                  chooseAfterValueNew[0] + "-" + chooseAfterValueNew[1]
                );
                $("#type").val(1);
                layer.close(index);
                return false;
              }
            },
          });
        } else if (flagg == 2) {
          $("#meetingTime").html();
          layer.open({
            title: "",
            type: 1,
            fix: false,
            skin: "layui-layer-rim",
            // 加上边框
            area: ["45%", "52%"],
            // 宽高
            content: $("#outChangeTimeForm").html(),
            success: function (layero, index) {
              $.ajax({
                type: "GET",
                async: true, //异步执行
                url: base_url + "/meeting/offlineMeetings/" + value,
                headers: {
                  Accept: "application/json; charset=utf-8",
                  Authorization: layui.sessionData("userToken").key,
                },
                success: function (data) {
                  if (data.type == "success") {
                    $("#changeAddress").empty();
                    result = data.data;
                    $.each(data.data, function (index, item) {
                      $("#changeAddress").append(new Option(index));
                    });
                    form.on(
                      "select(changeAddressFilter)",
                      renderDatePick($("#changeAddress").val())
                    );
                    form.on("select(changeAddressFilter)", function (data) {
                      changeMeetingAdress = data.value;
                      renderDatePick(data.value);
                    });
                    form.render("select");
                  }
                  $(".changeTimeAdd").show();
                },
              });
              element.on("tab(onChangeAddress)", function (data) {
                onChangeAddressIndex = data.index;
                changeAdderess(onChangeAddressIndex);
              });
            },
            cancel: function (index, layero) {
              changeAdderess(onChangeAddressIndex);
              layer.close(index);
              return false;
            },
          });
        }
      },
    });
    var onChangeAddressIndex = "";
    function changeAdderess(onChangeAddressIndex) {
      if (onChangeAddressIndex === 1) {
        form.on("select(changeAddressN)", function (data) {
          $("#meetAdderss").val(data.value);
        });
        renderData();
        $("#type").val(3);
      } else {
        var chooseAfterValueNew = indexItem.sort((a, b) => {
          return a > b ? 1 : -1;
        });
        if (chooseAfterValueNew.length == 0) {
          $("#meetingTime").html($("#changeAddress option:selected").val());
        } else {
          $("#meetingTime").html(
            chooseAfterValueNew[0] +
              "-" +
              chooseAfterValueNew[1] +
              " " +
              $("#changeAddress option:selected").val()
          );
        }

        $("#meetAdderss").val($("#changeAddress").text().trim());
        $("#type").val(2);
      }
    }

    //周六周日不可选
    function disabled_date(value, appointmentDate) {
      var mm = value.year + "-" + value.month + "-" + value.date;
      $(".laydate-theme-grid table tbody")
        .find('[lay-ymd="' + mm + '"]')
        .removeClass("layui-this");
      if (appointmentDate != null && appointmentDate != "") {
        var dates = appointmentDate.split(",");
        for (var i = 0; i < dates.length; i++) {
          if (dates[i] == "7") {
            dates[i] = 0;
          }
          $("table>tbody>tr")
            .find("td:eq(" + dates[i] + ")")
            .addClass("laydate-disabled");
        }
      }
    }
    function renderData() {
      $(".changeTimeBar ul").html();
      var html = "";
      var timePoint = [
        "08:00",
        "08:30",
        "09:00",
        "09:30",
        "10:00",
        "10:30",
        "11:00",
        "11:30",
        "12:00",
        "12:30",
        "13:00",
        "13:30",
        "14:00",
        "14:30",
        "15:00",
        "15:30",
        "16:00",
        "16:30",
        "17:00",
        "17:30",
        "18:00",
      ];
      for (var i = 0; i < timePoint.length; i++) {
        html += '<button  type="button">' + timePoint[i] + "</button>";
      }
      $(".changeTimeBar ul").html(html);
      // let indexItemm = [];
      let indexDataa = [];
      let timeItemm = [];
      $(".changeTimeBar ul button").on("click", function () {
        let valueText = $(this).text();
        let indexId = $(this).index();
        indexItemm.push(valueText);
        indexDataa.push(indexId);

        if (indexItemm.length == 1) {
          $(this).css("background-color", "#e79e4c");
        } else if (indexItemm.length == 2) {
          indexDataa.sort((a, b) => {
            return a - b;
          });
          var arr = timePoint.slice(indexDataa[0] + 1, indexDataa[1]);
          var ffd = arr.map((item, index) => {
            return timeItemm.includes(item);
          });
          if (ffd.indexOf(true) > -1) {
            var startIndex = indexDataa[0];
            var endIndex = indexDataa[1];
            $(".changeTimeBar ul button")
              .eq(startIndex)
              .css("background-color", "rgb(192, 206, 235)");
            $(".changeTimeBar ul button")
              .eq(endIndex)
              .css("background-color", "rgb(192, 206, 235)");
            indexItem.length = 0;
            indexDataa.length = 0;
            indexItem.push(valueText);
            indexDataa.push(indexId);
            $(this).css("background-color", "#e79e4c");
          } else {
            var startIndex = indexDataa[0];
            var endIndex = indexDataa[1];
            getIndex(startIndex, endIndex + 1);
          }
        } else {
          var startIndex = indexDataa[0];
          var endIndex = indexDataa[1];
          clearIndex(startIndex, endIndex + 1);

          indexItemm.length = 0;
          indexDataa.length = 0;
          indexItemm.push(valueText);
          indexDataa.push(indexId);
          $(this).css("background-color", "#e79e4c");
        }

        function getIndex(startIndex, endIndex) {
          if (startIndex < endIndex) {
            $(".changeTimeBar ul button")
              .eq(startIndex)
              .css("background-color", "#e79e4c");
            startIndex++;
            getIndex(startIndex, endIndex);
          }
        }
        function clearIndex(startIndex, endIndex) {
          if (startIndex < endIndex) {
            $(".changeTimeBar ul button")
              .eq(startIndex)
              .css("background-color", "rgb(192, 206, 235)");
            startIndex++;
            clearIndex(startIndex, endIndex);
          }
        }
      });
    }
    function renderDatePick(roomKey) {
      $(".changeTimeBar ul").html();
      let times = result[roomKey];
      let timeItem = [];
      var timePoint = [
        "08:00",
        "08:30",
        "09:00",
        "09:30",
        "10:00",
        "10:30",
        "11:00",
        "11:30",
        "12:00",
        "12:30",
        "13:00",
        "13:30",
        "14:00",
        "14:30",
        "15:00",
        "15:30",
        "16:00",
        "16:30",
        "17:00",
        "17:30",
        "18:00",
      ];
      var html = "",
        disabled = false,
        flgVal = true;
      for (var i = 0; i < timePoint.length; i++) {
        let flag = false;
        for (var j = 0; j < times.length; j++) {
          let time = times[j];
          flag =
            timePoint[i] >= time["startTime"] &&
            timePoint[i] <= time["endTime"];
          if (flag) {
            selectedDataList.push(timePoint[i]);
            break;
          }
        }
        if (flag) {
          timeItem.push(timePoint[i]);
          html +=
            '<button  type="button" class="active" disabled=' +
            !disabled +
            ">" +
            timePoint[i] +
            "</button>";
        } else {
          html += '<button type="button" >' + timePoint[i] + "</button>";
        }
      }
      $(".changeTimeBar ul").html(html);
      $(".changeAddBar").html(roomKey);
      let chooseAfterValue = [];
      // let indexItem = [];
      let indexData = [];
      $(".changeTimeBar ul button").on("click", function () {
        let valueText = $(this).text();
        let indexId = $(this).index();
        indexItem.push(valueText);
        indexData.push(indexId);

        if (indexItem.length == 1) {
          $(this).css("background-color", "#e79e4c");
        } else if (indexItem.length == 2) {
          indexData.sort((a, b) => {
            return a - b;
          });
          console.log(indexData);
          var arr = timePoint.slice(indexData[0] + 1, indexData[1]);
          var ffd = arr.map((item, index) => {
            return timeItem.includes(item);
          });
          if (ffd.indexOf(true) > -1) {
            var startIndex = indexData[0];
            var endIndex = indexData[1];
            $(".changeTimeBar ul button")
              .eq(startIndex)
              .css("background-color", "rgb(192, 206, 235)");
            $(".changeTimeBar ul button")
              .eq(endIndex)
              .css("background-color", "rgb(192, 206, 235)");
            indexItem.length = 0;
            indexData.length = 0;
            indexItem.push(valueText);
            indexData.push(indexId);
            $(this).css("background-color", "#e79e4c");
          } else {
            var startIndex = indexData[0];
            var endIndex = indexData[1];
            getIndex(startIndex, endIndex + 1);
          }
        } else {
          var startIndex = indexData[0];
          var endIndex = indexData[1];
          clearIndex(startIndex, endIndex + 1);

          indexItem.length = 0;
          indexData.length = 0;
          indexItem.push(valueText);
          indexData.push(indexId);
          $(this).css("background-color", "#e79e4c");
        }

        function getIndex(startIndex, endIndex) {
          if (startIndex < endIndex) {
            $(".changeTimeBar ul button")
              .eq(startIndex)
              .css("background-color", "#e79e4c");
            startIndex++;
            getIndex(startIndex, endIndex);
          }
        }
        function clearIndex(startIndex, endIndex) {
          if (startIndex < endIndex) {
            $(".changeTimeBar ul button")
              .eq(startIndex)
              .css("background-color", "rgb(192, 206, 235)");
            startIndex++;
            clearIndex(startIndex, endIndex);
          }
        }
      });
      // $(".changeTimeAdd .closeBtn").on("click", function () {
      //   $(".changeTimeAdd").hide();
      //   var chooseAfterValueNew = indexItem.sort((a, b) => {
      //     return a > b ? 1 : -1;
      //     // return  a-b
      //   });
      //   $("#changeDateS").val(chooseAfterValueNew[0]);
      //   $("#changeDateE").val(chooseAfterValueNew[1]);
      //   $("#changeDateA").val($("#changeAddress").text().trim());
      // });
    }
  }

  exports("meetingsManagement", {});
});
